package pt.utl.ist.ginger3d;

import java.io.IOException;
import java.io.RandomAccessFile;

/*
 *  TODO: 
 *  currently little endian, but this must be parameterized in the future
 *  also all the numbers are signed by java convention
 *  for unsigned values we must use the type above (ie. if  int, use long)
 *  file ending semantics (return -1, fail-safe conditions?)
 */

public class BinaryFileReader {

	RandomAccessFile braf;
	int offset = 0;

	public BinaryFileReader(String filePath) throws IOException {
		braf = new BufferedRandomAccessFile(filePath, "r");
	}

	public int readInt() throws IOException {
		byte[] ba = new byte[4];
		braf.read(ba);
		int v = 0;
		for (int i = 0; i < 4; i++) {
			v |= (ba[i] & 0xFF) << (i * 8);
		}
		offset += 4;
		return v;
	}

	public long readLong() throws IOException {
		return readInt() | ((long) readInt() << 32);
	}

	public short readShort() throws IOException {
		return (short) (readByte() | ((readByte()) << 8));
	}

	public byte readByte() throws IOException {
		offset += 1;
		int rst = braf.read();
		return(rst == -1) ? -1 : (byte) rst; 
	}

	public String readString() throws IOException {
		return readString(4);
	}

	public String readString(int numBytes) throws IOException {
		byte[] ba = new byte[numBytes];
		int rst = braf.read(ba);
		if(rst == -1) {
			return "-1";
		}
		return new String(ba);
	}

	protected void finalize() throws Throwable {
		braf.close();
	}
	
	public long getOffset() throws IOException {
		return braf.getFilePointer();
	}
	
	public void setOffset(long offset) throws IOException {
		braf.seek(offset);
	}
	
	public void addOffset(long offset) throws IOException {
		braf.seek(getOffset()+offset);
	}
}
